package com.hejing.TCP与UDP网络编程;

import org.junit.Test;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.*;

/**
 * ClassName: UDPTest
 * Package: com.hejing.TCP与UDP网络编程
 * Description:
 *
 * @Author: HeJing
 * @Create: 2023-06-02 22:03
 * @Version: 1.0
 */
public class UDPTest {

    /**
     * 发送端
     */
    @Test
    public void sender(){

        DatagramSocket ds = null;
        try {
            // 1、创建DatagramSocket实例
            ds = new DatagramSocket();

            // 2、将数据、目的地端口号都封装在DatagramPacket中
            InetAddress inetAddress = InetAddress.getByName("127.0.0.1");
            int port = 9090;
            byte[] bytes = "我是发送端".getBytes("utf-8");
            // 数据报
            DatagramPacket packet = new DatagramPacket(bytes, 0, bytes.length, inetAddress, port);
            ds.send(packet);

            System.out.println("发送数据完毕...");
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (SocketException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            ds.close();
        }

    }

    /**
     * 接收端
     */
    @Test
    public void receiver(){
        DatagramSocket ds = null;

        try {
            // 1、创建DatagramSocket实例
            int port = 9090;
            ds = new DatagramSocket(port);

            // 2、创建数据报对象，用于接收发送端发送过来的数据。
            byte[] buffer = new byte[1024*64];
            DatagramPacket packet = new DatagramPacket(buffer, 0, buffer.length);

            // 3、接收数据
            ds.receive(packet);

            // 4、获取数据并打印
            String str = new String(packet.getData(), 0, packet.getLength());
            System.out.println(str);

            System.out.println("接收数据完毕...");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            ds.close();
        }


    }
}






















